import { createRouter, createWebHashHistory } from 'vue-router'
import routerStore, { ActiveType } from '@/stores/routerStore'
import { RouteType } from '@/types/router'
import useInitRouter from '@/hooks/useInitRouter'
import { adminConfig } from "@Tea/model"
import { defaultRoutes } from './index'
import { getLocalStorage } from '@Tea/utils'
import useInitUserInfo from '@/hooks/useInitUserInfo'

// 3. 创建路由实例并传递 `routes` 配置
const router = createRouter({
  //  内部提供 history 模式的实现。 
  history: createWebHashHistory(),
  routes: defaultRoutes
})

router.beforeResolve((to, from, next) => {
  if (to.path === '/login') { next() }
  else if (router.hasRoute('app')) {
    const store = routerStore()
    
    if (typeof to.name === "string") {
      store.changeTargetRoute({ name: to.name, ...to.meta } as ActiveType)
    }
    
    next()
  }
  else {
    const routeTree = getLocalStorage(`${adminConfig.systemCode}-routeTree`)  //JSON.parse(localStorage.getItem('') as string)
    if (routeTree == undefined) {
      next({ name: 'login' })
      return
    } 
    
    useInitRouter(router, routeTree as RouteType)
    useInitUserInfo(getLocalStorage(`${adminConfig.systemCode}-user`))
    next({ ...to, replace: true });
  }
})


export default router